package org.zizi.manager;

import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.zizi.util.Options;

public class Managers
{
	private static final Logger log = Logger.getLogger(Managers.class);
	
	private static Map<Class<?>, Manager> map = new HashMap<Class<?>, Manager>();
	private static List<Manager> managers = new LinkedList<Manager>();
	
	public static <T> T get(Class<T> type)
	{
		Manager m = map.get(type);
		if (m == null) log.warn("管理器不存在：" + type.getName());
		return type.cast(m);
	}
	
	public static void initialize(Options options) throws Exception
	{
		for (Manager m : managers) m.initialize(options);
	}
	
	public static void destroy()
	{
		Collections.reverse(managers);
		for (Manager m : managers) m.destory();
		
		managers.clear();
		map.clear();
	}
	
	///////
	public static void add(Class<? extends Manager> type) throws Exception
	{
		//若存在，则警告
		if (map.get(type) != null) log.warn("重复添加管理器：" + type.getName());
		else log.info("添加管理器：" + type.getName());
		
		Manager m = type.newInstance();
		
		//按接口添加
		for (Class<?> c : type.getInterfaces())
		{
			if (!Manager.class.isAssignableFrom(c)) continue;
			if (Manager.class.equals(c)) continue;
			
			map.put(c, m);
		}
		//接类添加
		for (Class<?> c = type; Manager.class.isAssignableFrom(c); c = c.getSuperclass())
		{
			if (Manager.class.equals(c)) continue;
			
			map.put(c, m);
		}
		
		managers.add(m);
	}
}
